import { action, observable } from 'mobx';
import {
  listRole,
  saveRole,
  deleteRole,
  listRoleModule,
  updateRoleModule,
} from '../service';
import loading from '../../../components/Loading';
import { message } from 'antd';
import { listDept } from '../../dept/service';

class AppStore {
  // 角色列表参数
  @observable roleListData = {
    dataSource: [],
    loading: false,
  };

  // 角色资源参数
  @observable moduleDrawerData = {
    loading: false,
    visible: false,
    moduleList: [],
  };

  // 角色弹出框参数
  @observable roleDialogData = {
    loading: false,
    visible: false,
    editData: {},
  };


  @action
  async orgOnload(row) {
    this.roleListData.dataSource = await loading(listRole, this.roleListData)(row.id);
  }
  @action
  async selectOrg(key) {
    this.roleListData.dataSource = await loading(listRole, this.roleListData)(key);
  }
  /**
   * 打开授权资源窗口
   * @param record 角色记录
   */
  async editRoleModule(role, disabled) {
    // 弹出授权资源抽屉
    this.moduleDrawerData = { role: role, moduleList: await listRoleModule(role.id), visible: true, disabled: disabled };
  };

  /**
   * 关闭抽屉
   */
  @action
  closeDrawer() {
    this.moduleDrawerData = { ...this.moduleDrawerData, visible: false };
  };

  @action
  checkModuleTree(checkedKeys) {
    this.moduleDrawerData = { ...this.moduleDrawerData, moduleList: checkedKeys };
  }

  /**
   * 保存资源数据，并关闭抽屉
   * @param res
   * @returns {Promise<void>}
   */
  @action
  async updateRoleModule() {
    let resArray = this.moduleDrawerData.moduleList;
    await loading(updateRoleModule, this.moduleDrawerData)({
      roleId: this.moduleDrawerData.role.id,
      moduleList: resArray.join(','),
    });
    this.closeDrawer();
  };

  @action
  showRoleDialog(params) {
    this.roleDialogData = { ...this.roleDialogData, visible: true, editData: params ? params : {} };
  }

  @action
  closeRoleDialog() {
    this.roleDialogData.visible = false;
  }

  @action
  async saveRole(data) {
    await loading(saveRole, this.roleDialogData)(data);
    this.roleListData.dataSource = await loading(listRole, this.roleListData)(data.orgId);
    this.roleDialogData = { ...this.roleDialogData, visible: false };
    message.info('保存角色成功');
  }

  /**
   * 删除角色响应函数
   * @param record 角色
   */
  async deleteRole(record) {
    await deleteRole(record.id);
    this.roleListData.dataSource = await loading(listRole, this.roleListData)(record.orgId);
  };

  /**
   * 根据角色名称模糊查询角色列表
   * @param name 角色名称
   */
  @action
  async searchRole(orgId, name) {
    this.roleListData.loading = true;
    this.roleListData = { dataSource: await listRole(orgId, name), loading: false };
  };
}

export default AppStore;
